package com.briup.jd2511.jd2511bookstore.config;

import com.briup.jd2511.jd2511bookstore.interceptor.LoginCheckInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域配置类
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    // 注入拦截器
    @Autowired
    private LoginCheckInterceptor loginCheckInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 对swagger的请求不进行拦截
        String[] excludePatterns = new String[]{
                "/profile/**",
                "/common/download**",
                "/common/download/resource**",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/webjars/**",
                "/*/api-docs/**",
                "/favicon.ico",
                "/doc.html",
                "/error","/static/**","/login"
        };
        // 添加拦截器
        registry.addInterceptor(loginCheckInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludePatterns);

    }

    /**
     * 静态资源配置
     */
//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry) {
////        registry.addResourceHandler("/css/**").addResourceLocations("classpath:/css/");
////        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
////        registry.addResourceHandler("/pages/**").addResourceLocations("classpath:/pages/");
////        registry.addResourceHandler("/elementui/**").addResourceLocations("classpath:/elementui/");
////        registry.addResourceHandler("/image/*/**").addResourceLocations("classpath:/static/image/*/**");
//
//        // knife4j页面的白名单
//        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
//        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
//    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT","HEAD","OPTIONS")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }
}
